<template>
  <div>
    <Header :left="true" leftText="返回" title="任务列表" />
    <div>
      <van-row style="margin-top: 80px">
        <van-col><van-image width="40" height="30" style="margin-left: -10px" src="assets/block.png" /></van-col>
        <van-col class="message">任务清单</van-col>
        <van-icon right name="enlarge" size="1.5em" @click="showScanner"
          style="margin-top: 2px; float: right; margin-right: 2px"></van-icon>
      </van-row>
    </div>
    <div class="textScroll">
      <!-- 循环数据开始 -->
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <div v-for="item in itemsOne" :key="item.id">
          <div style="width: 100%; background-color: #f3f4f8; height: 5px">
            <span></span>
          </div>
          <div class="divStyle" @click="showDetail(item)">
            <!-- <van-row style="margin-top:10px;">
              <van-col span="15" style="margin-left:5px;font-weight:bold;font-size:15px;color:#A9A9A9;"
                >任务单号：{{ item.taskCode }}</van-col
              >
            </van-row>
            <van-row style="margin-top:10px;">
              <van-col span="24" style="margin-left:5px;color:#A9A9A9;font-size:15px;"
                >创建时间：<van-icon name="assets/time.png" /> {{ item.createTime }}</van-col
              >
            </van-row> -->

            <!-- <van-divider style="margin-top:10px;" /> -->
            <van-row style="margin-top: 10px; font-size: 18px">
              <van-col span="24" style="color: #a9a9a9; margin-left: 5px">设备编码：{{ item.eqCode }}
                <div @click.stop="" style="margin-top: -23px">
                  <Button style="float: right; height: 30px" @click.prevent="showDetailMessage(item)" color="#138087">查看详情
                  </Button>
                  <!-- <Button
                    style="float: right; height: 30px"
                    @click.prevent="deletetask(item)"
                    color="linear-gradient(to right, #FF0000, #FF0000)"
                    >任务取消
                  </Button> -->
                </div>
              </van-col>
              <van-col span="15" style="color: #a9a9a9; margin-top: 10px; margin-left: 5px">设备名称：{{ item.eqName }}
              </van-col>
              <van-col span="8">
                <div class="labelStyle">
                  {{ item.progress }}
                </div>
              </van-col>
            </van-row>
          </div>
        </div>
      </van-list>

      <!-- 循环数据结束//statusList[item.status]  -->
    </div>
    <!-- 详情弹窗 -->
    <van-dialog v-model="detailShow" style="height: 240px" title="详情">
      <div style="height: 130px">
        <van-row style="margin-top: 10px">
          <van-col span="24" style="
              margin-left: 5px;
              font-weight: bold;
              font-size: 18px;
              color: #a9a9a9;
            ">任务单号：{{ detailMessage.taskCode }}</van-col>
        </van-row>
        <van-row style="margin-top: 10px">
          <van-col span="24" style="margin-left: 5px; color: #a9a9a9; font-size: 18px">创建时间：<van-icon
              name="assets/time.png" />
            {{ detailMessage.createTime }}</van-col>
        </van-row>
        <van-col span="15" style="
            color: #a9a9a9;
            margin-top: 10px;
            margin-left: 5px;
            font-size: 18px;
          ">执行部门：{{ detailMessage.department }}</van-col>
        <van-col span="15" style="
            color: #a9a9a9;
            margin-top: 10px;
            margin-left: 5px;
            font-size: 18px;
          ">设备状态：{{ eqstatusList[detailMessage.eqStatus] }}</van-col>
      </div>
    </van-dialog>
  </div>
</template>
<script>
import {
  Icon,
  Button,
  CellGroup,
  Cell,
  Field,
  tab,
  tabs,
  Col,
  Row,
  Image as VanImage,
  Divider,
  Checkbox,
  Pagination,
  Panel,
  Toast,
  Dialog,
  List,
} from "vant";
import { _httpClient } from "@/libs/api";
import { storage } from "@/libs/utils";
import {
  removeToken,
  getToken,
  setBaseApiFrefix,
  getBaseApiFrefix,
} from "@/libs/auth";
import { memory } from "@/libs/utils";
Vue.use(Cell);
Vue.use(CellGroup);
Vue.use(tab);
Vue.use(tabs);
Vue.use(Button);
Vue.use(Col);
Vue.use(Row);
Vue.use(Icon);
Vue.use(VanImage);
Vue.use(Divider);
Vue.use(Checkbox);
Vue.use(Pagination);
Vue.use(Panel);
Vue.use(Dialog);
Vue.use(List);
import Header from "@/components/header.vue";
import apicloud from "@/libs/apicloud";

export default {
  components: {
    Button,
    Header,
    Icon,
    CellGroup,
    Cell,
    Field,
    tab,
    tabs,
    Col,
    Row,
  },

  data() {
    return {
      detailShow: false, //详情展示弹窗
      queryParams: [], //传递参数
      //动态加载数据
      loading: false,
      finished: false,
      user: [], //登录用户信息
      //下拉刷新动态
      loadParams: {
        pageNum: 1,
        pageSize: 5,
        total: 0,
      },
      detailMessage: [], //详情信息
      currentEquipName: "",
      allSelected: false,
      selectFont: "一键勾选",
      screenWidth: 0,
      checked: true,
      active: 2,
      currentPage: 1,
      fileUrl: "",
      itemsOne: [
        // {
        //   searchValue: null,
        //   params: {},
        //   siteKey: 21486,
        //   taskCode: "DJ20201224000306",
        //   eqKey: 216486,
        //   taskType: "0",
        //   taskCategory: null,
        //   eqStatus: "0",
        //   status: "0",
        //   createTime: "2020-12-24 11:38:14",
        //   executer: null,
        //   startTime: null,
        //   endTime: null,
        //   workTime: null,
        //   department: "工程部",
        //   eqCode: "SAPCP07/CYQ17",
        //   eqName: "吹瓶机",
        //   eqType: null,
        // },
      ],
      statusList: { 0: "待执行", 1: "执行中", 2: "完成", 3: "系统标记完成" }, //状态数组
      eqstatusList: { 0: "停机", 1: "运行" },
    };
  },
  created: function () {
    let oldHight = api.winWidth;
    this.screenWidth = oldHight;
    //获取当前系统登录用户
    this.user = JSON.parse(storage.get("user"));
    api.requestPermission(
      {
        list: ["camera", "microphone", "storage"],
      },
      function (ret, err) { }
    );

    // try {
    //   var manageStorage = api.require('manageStorage');
    //   manageStorage.requestAllFilePermission({
    //   }, function (ret) {
    //     // api.alert({
    //     //   msg: JSON.stringify(ret)
    //     // })
    //   });
    // } catch {

    // }
    
    //获取传递参数
    this.queryParams = api.pageParam;

    let tkn = getToken();
    if (!tkn) {
      api.openWin({
        name: "login",
        url: "./login-login.html",
        rect: {
          x: 0,
          y: 150,
          w: api.winWidth,
          h: api.winHeight,
        },
      });
    }

    //如果当前界面没有设备编码，打开扫描界面
    if (this.currentEquipName == "") {
      this.showScanner();
    }
  },
  methods: {
    //详情展示
    showDetailMessage(item) {
      this.detailMessage = item;
      this.detailShow = true;
    },
    async deletetask(item) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      _this.detailMessage = item;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/equip/check/closetask",
          {
            body: {
              taskCode: _this.detailMessage.taskCode,
              userId: this.user.userId,
            },
          }
        );

        if (res.code === 200) {
          Toast.clear();
          _this.queryWaitRepairList();

          Toast.success("取消任务成功");
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        alert(JSON.stringify(e));
        Toast.fail(JSON.stringify(e));
      }
    },
    //任务列表动态加载
    onLoad() {
      //页数+1
      this.loadParams.pageNum = this.loadParams.pageNum + 1;
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        // this.queryWaitRepairList()
        // 加载状态结束
        this.loading = true;

        // 数据全部加载完成
        // if (this.itemsOne.length >= this.loadParams.total) {
        //   this.finished = true
        // }
      }, 100);
    },

    //进入点检执行界面
    showDetail(item) {
      let _this = this;
      //查询点检项相关信息
      _this.queryTask({
        body: {
          taskCode: item.taskCode,
          siteKey: _this.user.site,
          eqStatus:
            _this.queryParams.taskType == "2"
              ? null
              : _this.queryParams.eqStatus,
          taskType: _this.queryParams.taskType,
          equipCode: _this.currentEquipName,
        },
      });
      //跳转到点检页面
      // this.$ac.openWin({
      //   name: 'equip_check',
      //   url: './demos-equip_check.html',
      //   pageParam: {
      //     equipCode: item.eqCode,
      //     taskItemList: res.taskItemList,
      //     taskFileList: res.taskFileList,
      //   },
      // })
      // api.addEventListener(
      //   {
      //     name: 'result',
      //   },
      //   function(ret, err) {
      //     if (ret.value.item.length != 0) {
      //       for (let i = 0; i < _this.itemsOne.length; i++) {
      //         if (_this.itemsOne[i].id == ret.value.item.id) {
      //           _this.itemsOne.splice(i, 1)
      //         }
      //       }
      //     }
      //   }
      // )
    },

    async queryTask(data) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });
      let that = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/equip/check/isExist",
          data
        );
        Toast.clear();
        if (res.code === 200) {
          if (res.taskItemList) {
            //跳转到点检页面
            this.$ac.openWin({
              name: "equip_check",
              url: "./maintain-spotCheck-equip_check.html",
              pageParam: {
                equipCode: data.body.equipCode,
                taskItemList: res.taskItemList,
                taskFileList: res.taskFileList,
              },
            });
            //监听页面返回
            api.addEventListener(
              {
                name: "result",
              },
              function (ret, err) {
                if (
                  ret.value.taskCode != "" &&
                  ret.value.taskCode != undefined
                ) {
                  for (let i = 0; i < that.itemsOne.length; i++) {
                    if (that.itemsOne[i].taskCode == ret.value.taskCode) {
                      that.itemsOne.splice(i, 1);
                    }
                  }
                }
              }
            );
          } else {
            that.$ac.confirm(
              {
                title: "创建任务",
                msg: "没有找到相关任务，请问需要创建吗？",
                buttons: ["确定", "取消"],
              },
              function (ret, err) {
                if (ret.buttonIndex == 1) {
                  //创建任务
                  that.creatTask(data);
                }
              }
            );
          }
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    //初始化查询待执行任务
    queryWaitRepairList() {
      let _this = this;
      _this.finished = false;
      if (_this.currentEquipName == "") {
        return;
      }

      if (_this.user == "" || _this.user == undefined) {
        Dialog.alert({
          theme: "round-button",
          message: "获取当前登录用户失败，请重新登录系统",
        }).then(() => {
          // on close
        });
        return;
      }
      api.ajax(
        {
          url: _httpClient.getApiPrefix() + "/equip/check/pointTaskList",
          //如果地址访问不到会请求出错，请填写自己的接口地址
          method: "post",
          cache: "false",
          timeout: 30,
          dataTpye: "json",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            Authorization: "Bearer " + getToken(),
          },
          data: {
            body: {
              eqStatus:
                _this.queryParams.taskType == "2"
                  ? null
                  : _this.queryParams.eqStatus,
              taskType: _this.queryParams.taskType,
              eqCode: _this.currentEquipName,
              //工厂和对应部门任务
              siteKey: _this.user.site,
              department: _this.user.dept.deptName,
            },
          },
        },
        function (res, err) {
          if (res.code === 200) {
            // alert(res.rows[0]);
            // if ((this.itemsOne = [])) {
            // debugger
            // alert(res.rows[0]);
            _this.loadParams.total = res.total;
            _this.itemsOne = res.rows;
            //判断是否已加载完成
            if (_this.itemsOne.length >= _this.loadParams.total) {
              _this.finished = true;
            }

            // //判断是否已加载完成
            // if (_this.itemsOne.length >= _this.loadParams.total) {
            //   _this.finished = true
            //   return
            // }
            // for (let i = 0; i < res.rows.length; i++) {
            //   _this.itemsOne.push(res.rows[i])
            // }
            //}
          } else {
            if (res.code == 401) {
              Dialog.confirm({
                title: "提示",
                theme: "round-button",
                message: "登录状态已过期，您可以继续留在该页面，或者重新登录?",
              })
                .then(() => {
                  api.openWin({
                    name: "login",
                    url: "./login-login.html",
                    rect: {
                      x: 0,
                      y: 150,
                      w: api.winWidth,
                      h: api.winHeight,
                    },
                  });
                })
                .catch(() => { });
              return;
            }
            Toast.clear();
            Dialog.alert({
              message: res.msg,
              theme: "round-button",
            }).then(() => { });
          }
        }
      );
    },

    //打开扫描
    showScanner() {
      let _this = this;
      _this.itemsOne = [];
      if (
        api.deviceName.toLowerCase() == "huawei" ||
        api.deviceName.toLowerCase() == "honor"
      ) {

        // _this.currentEquipName = ret.result;
        //       _this.queryWaitRepairList();

        var zyHmsScan = api.require('zyHmsScan');
        var param = {
          //returnAll:true
        };
        zyHmsScan.openDefaultView(param, function (ret) {
          //_this.addBarCode(ret.result);
          _this.currentEquipName = ret.result;
          _this.queryWaitRepairList();
          //api.alert({ msg: JSON.stringify(ret) });
        });

        // var QRScan = api.require("QRScan");
        // QRScan.customizedScanner(
        //   {
        //     rect: {
        //       x: 15, //（可选项）数字类型；模块左上角的 x 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       y: 0, //（可选项）数字类型；模块左上角的 y 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       w: 320, //（可选项）数字类型；模块的宽度；支持设置'auto'；默认：所属的 Window 或 Frame 的宽度
        //       h: 480, //（可选项）数字类型；模块的高度；支持设置'auto'；默认：所属的 Window 或 Frame 的高度
        //     },
        //     rectOfInterest: {
        //       x: 64, //（可选项）数字类型；扫码识别区域左上角的 x 坐标（相对于扫码区rect）；默认：0
        //       y: 65, //（可选项）数字类型；扫码识别区域左上角的 y 坐标（相对于扫码区rect）；默认：0
        //       w: 250, //（可选项）数字类型；扫码识别区域的宽度；默认：扫码区rect的宽度
        //       h: 250, //（可选项）数字类型；扫码识别区域的高度；默认：扫码区rect的高度
        //     },
        //     //tipString:'放入框内扫码',
        //     maskColor: "rgba(0,0,0,0.5)",
        //     scanLine: {
        //       color: "#00FF00",
        //       thickness: 2,
        //     },
        //     marginB: 30,
        //     formatType: "ALL",
        //   },
        //   function (ret) {
        //     if (ret) {
        //       let res = ret.result.split(",");
        //       _this.currentEquipName = ret.result;
        //       _this.queryWaitRepairList();
        //     }
        //   }
        // );
        //    QRScan.closeCustomizedScanner();
      } else {
        var FNScanner = _this.$ac.require("FNScanner");
        FNScanner.openScanner(
          {
            autorotation: true,
          },
          function (ret, err) {
            if (ret) {
              if (ret.eventType == "success" && ret.content != "") {
                let res = ret.content.split(",");
                _this.currentEquipName = ret.content;
                _this.queryWaitRepairList();
              }
            } else {
              alert(JSON.stringify(err));
            }
          }
        );
      }
    },
    // showScanner() {
    //   let _this = this;
    //   _this.itemsOne = [];
    //   var ACScanner = api.require("ACScanner");
    //   ACScanner.openScan(
    //     {
    //       scanAnim: {
    //         w: 350,
    //         h: 350,
    //       },
    //     },
    //     function (ret, err) {
    //       if (ret) {
    //         if (ret.eventType == "success" && ret.content != "") {
    //           _this.currentEquipName = ret.content;
    //           _this.queryWaitRepairList();
    //           ACScanner.closeScan();
    //         }
    //       } else {
    //         alert(JSON.stringify(err));
    //       }
    //     }
    //   );
    // },
  },
};
</script>
<style>
html,
body {
  background-color: White;
}

.pic {
  width: 100%;
  text-align: center;
}

.clickbtn {
  width: 1;
  margin: 5px 10px;
  line-height: 45px;
  border: 1px #ccc dashed;
  text-align: center;
}

.buttonRight {
  position: fixed;
  margin-top: -40px;
  right: 10px;
  width: 88px;
  height: 40px;
  background-color: #1c6c8d;
  border-color: #1c6c8d;
}

.buttonLeft {
  position: fixed;
  margin-top: -40px;
  right: 100px;
  width: 88px;
  height: 40px;
  background-color: #1c6c8d;
  border-color: #1c6c8d;
}

.message {
  font-size: 15px;
  margin-top: 5px;
  margin-left: -10px;
  font-weight: bold;
}

.divStyle {
  /* border: solid #dcdcdc; */
  border-top-width: 3px;
  border-right-width: 0px;
  border-left-width: 0px;
  margin-left: 5px;
  margin-right: 4px;
  height: 80px;
  margin-top: 4px;
}

.pagination {
  position: fixed;
  bottom: 15px;
  width: 300px;
  margin-left: 10%;
  color: rgb(0, 0, 255);
  text-align: center;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 7rem;
  bottom: 1px;
  overflow: scroll;
  right: 0;
  width: 100%;
  margin-bottom: 0rem;
  z-index: 1;
}

.labelStyle {
  width: 70px;
  height: 20px;
  background-color: #ff9933;
  color: white;
  float: right;
  font-size: 15px;
  text-align: center;
  margin-top: 5px;
  line-height: 20px;
}
</style>
